package com.ProcessManagement;

import com.FileManager.File_Manager;
import com.hardware.Clock;
import com.ui.ProcessSchedulerUI;
import javafx.application.Application;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class testDemo {
    //    读取AccessingVariables文件
    public static List<List<Integer>> readAccessingVariables (String fileName) {
        List<List<Integer>> sequences = new ArrayList<>();

        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = reader.readLine()) != null) {
                List<Integer> sequence = parseLine(line);
                sequences.add(sequence);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sequences;
    }

    //    读取AccessingVariables文件后数据处理
    private static List<Integer> parseLine(String line) {
        String[] tokens = line.split(",");
        List<Integer> sequence = new ArrayList<>();
        for (String token : tokens) {
            sequence.add(Integer.parseInt(token));
        }
        return sequence;
    }

    //    从List<List<Integer>>提起一行数据
    public static int[] getRowValues(List<List<Integer>> sequences, int rowIndex) {
        List<Integer> row = sequences.get(rowIndex);
        int[] rowValues = new int[row.size()];

        for (int i = 0; i < row.size(); i++) {
            rowValues[i] = row.get(i);
        }

        return rowValues;
    }

    public static void main(String[] args){
//        获取当前pcb列表
        PCBReader pcbReader = PCBReader.getInstance();
        List<PCB> pcbList = pcbReader.getPCBList();
        ArrayList<PCB> CopypcbList = new ArrayList<>(pcbList);
//        pcb就绪队列
        List<PCB> ReadyPcbList = new ArrayList<>();
//        创建时钟类，单例模式
        Clock clock = Clock.getInstance();
//        声明Scheduler
        Scheduler scheduler = new Scheduler();
//        选择调度算法
//        SchedulingAlgorithm.SJF或SchedulingAlgorithm.ROUND_ROBIN
        SchedulingAlgorithm choseScheduling = SchedulingAlgorithm.ROUND_ROBIN;
        scheduler.start(choseScheduling);
//        用于判断是否有新加的pcb
        boolean flag = false;
//        判断是否创建了Scheduler
        boolean IsScheduler = false;
        // 启动JavaFX应用程序
        Thread fxThread = new Thread(() -> Application.launch(ProcessSchedulerUI.class, args));
        fxThread.start();
//        使用标记
        int useflag = 1;
//        文件管理模块
        List<List<Integer>> read_sequences;
        int position = 100;

        while (true) {
            // 在这里可以根据当前时间执行其他操作
            Iterator<PCB> iterator = CopypcbList.iterator();
            while (iterator.hasNext()){
                PCB pcb = iterator.next();
                if (clock.getCurrentTime() >= pcb.getStartTimes()) {
                    int index = CopypcbList.indexOf(pcb);
                    ProcessSchedulerUI.updateReadyQueue("时间达到"+clock.getCurrentTime()+"；进程："+pcb.getProID()+"加入就绪列表!");
                    pcb.setPSW("Ready");  // 设置进程状态为Ready
                    ReadyPcbList.add(pcb);
//                    文件模块
                    File_Manager File = new File_Manager();
                    File.isInitialized = true;
                    read_sequences = readAccessingVariables("src/input/disk_scheduling.txt");
                    int[] read_list = getRowValues(read_sequences,0);
                    int totalTime;
                    totalTime = File.SSTF(read_list,position);
                    ProcessSchedulerUI.updatemanagement("SSTF总用时长："+totalTime);

                    if (choseScheduling == SchedulingAlgorithm.SJF){
                        //重新开始
                        scheduler.start(choseScheduling);
                    }
                    ProcessSchedulerUI.updateReadyQueue("当前就绪列表：");
//                    打印就绪列表
                    pcbReader.printfPCB(ReadyPcbList);
                    iterator.remove();
                    flag = true;
                }
            }
            if (ReadyPcbList == null || ReadyPcbList.isEmpty()){
//                ProcessSchedulerUI.updateProcessOutput("当前时间："+currentTime+"，CUP空闲!");
            }
            else {
                if (flag == true){
                    scheduler.setPCBList(ReadyPcbList);
//                    唤醒
                    scheduler.resume();
                    flag = false;
                }
            }

            // 为了避免过于频繁的检查，可以添加适当的延时
            try {
                Thread.sleep(500); // 每0.5秒检查一次
                if (ReadyPcbList == null || ReadyPcbList.isEmpty()){
                    ProcessSchedulerUI.updateProcessOutput("当前时间："+clock.getCurrentTime()+"，CUP空闲!");
                    if (useflag == 1){
                        //                    打印pcb列表
                        ProcessSchedulerUI.updatePCBList("读取PCB列表");
                        PCBReader.getInstance().printfPCBInfo();
                        useflag++;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}
